<template>
    <div>
<!--      面包屑导航-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>
      <!--    卡片视图区域-->
      <el-card>
        <!--      添加分类按钮-->
        <el-row>
          <el-col>
            <el-button type="primary" @click="showAddDialogVisible">添加分类</el-button>
          </el-col>
        </el-row>
<!--        表格区域-->
        <tree-table
          :data="cateList"
          :columns="columns"
          :selection-type="false"
          :expand-type="false"
          show-index
          border
        >
          <template slot="isOk" slot-scope="scope">
<!--            {{scope.row}}-->
            <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color: lightgreen"></i>
            <i class="el-icon-error" v-else style="color: red"></i>
          </template>
          <template slot="sort" slot-scope="scope">
            <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
            <el-tag type="warning" v-else>三级</el-tag>
          </template>
          <template slot="handle" slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除</el-button>
          </template>
        </tree-table>
<!--      分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="cateQueryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="cateQueryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      </el-card>
<!--      添加分类对话框-->
      <el-dialog
        title="提示"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed">
        <el-form :model="addRuleForm" :rules="addRuleFormRules" ref="addRuleFormRef" label-width="80px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addRuleForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
<!--            options为数据源-->
<!--            props 指定的配置对象-->
<!--            v-model选中的节点-->
            <el-cascader
              v-model="selectedKeys"
              :options="parentCateList"
              :props="cascaderProps"
              @change="parentHandleChange"
              clearable
              ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'Cate',
  data () {
    return {
      // 商品分类数据
      cateList: [],
      // 查询参数
      cateQueryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 10
      },
      // 总条数
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 定义为模板列
          type: 'template',
          // 定义为模板名称
          template: 'isOk'
        },
        {
          label: '排序',
          type: 'template',
          template: 'sort'
        },
        {
          label: '操作',
          type: 'template',
          template: 'handle'
        }
      ],
      // 添加分类对话框
      addDialogVisible: false,
      // 添加分类的表单数据对象
      addRuleForm: {
        // 添加的分类名称
        cat_name: '',
        // 父级分类id
        cat_pid: 0,
        // 分类当前层级
        cat_level: 0
      },
      // 添加分类的表单验证规则对象
      addRuleFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 添加分类父级节点数据
      parentCateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        // 配置触发选项 hover/click
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 选中的节点
      selectedKeys: []
    }
  },
  // 实例创建调用函数
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      // 调用接口数据
      const { data: res } = await this.$http.get('categories', { params: this.cateQueryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      // console.log(res.data.result)
      // 数据列表赋值给cateList
      this.cateList = res.data.result
      // 为总数据条数赋值
      this.total = res.data.total
    },
    // 监听每页条数的显示
    handleSizeChange (newSize) {
      this.cateQueryInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听页码的切换
    handleCurrentChange (newChange) {
      this.cateQueryInfo.pagenum = newChange
      this.getCateList()
    },
    // 打开添加分类对话框
    showAddDialogVisible () {
      // 获取父级分类列表
      this.getParentCateList()
      this.addDialogVisible = true
    },
    // 获取添加分类父级节点数据
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.parentCateList = res.data
      // console.log(res.data)
    },
    // 添加分类级联选择框发生变化
    parentHandleChange () {
      // console.log(this.selectedKeys)
      // selectedKeys中数组大于0 说明选中了父级
      if (this.selectedKeys.length > 0) {
        // 父级分类的id
        this.addRuleForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        // 当前分类的等级赋值
        this.addRuleForm.cat_level = this.selectedKeys.length
        return 0
      } else {
        // 父级分类的id
        this.addRuleForm.cat_pid = 0
        // 当前分类的等级赋值
        this.addRuleForm.cat_level = 0
      }
    },
    // 提交分类表单
    addCate () {
      // console.log(this.addRuleForm)
      this.$refs.addRuleFormRef.validate(async valid => {
        if (!valid) return
        // const { data: res } = await this.$http.post('categories', this.addRolesForm)
        const { data: res } = await this.$http.post('categories', this.addRuleForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        console.log(res)
        this.$message.success('添加成功')
        await this.getCateList()
        this.addDialogVisible = false
      })
    },
    // 添加分类表单关闭
    addDialogClosed () {
      this.$refs.addRuleFormRef.resetFields()
      // 清空级联的选择
      this.selectedKeys = []
      this.addRuleForm.cat_pid = 0
      this.addRuleForm.cat_level = 0
    },
    // 删除分类
    async deleteCate (cateId) {
      const resultCate = await this.$confirm('此操作将永久删除该文件, 是否继续?', '是否删除分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (resultCate !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      // 发起删除请求
      const { data: res } = await this.$http.delete(`categories/${cateId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除数据失败')
      }
      this.$message.success('删除分类成功')
      this.getCateList()
    }
  }
}
</script>

<style scoped>
.zk-table {
  font-size: 13px;
}
.el-row {
  margin-bottom: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
